/**
 * PlateNumberValidator.java 
 * Copyright © 2015-3015, 杭州泊享网络科技有限公司
 * 
 * @author Liu Tao
 * @create 2015年5月11日
 */
package com.pshare.framework.validator;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.apache.commons.lang3.StringUtils;

import com.pshare.constant.ReturnMsg;
import com.pshare.constant.SeaxConstants;
import com.pshare.framework.annotation.PlateNumberCheck;

/**
 * 车牌号码验证
 */
public class PlateNumberValidator implements ConstraintValidator<PlateNumberCheck, CharSequence> {

	private static String PLATE_NUMBER_FORMAT = "^(([\u4e00-\u9fa5]{1}[A-Z]{1})|(WJ(([\u4e00-\u9fa5]{1})|(\\d{0,2}))))[A-Z_0-9]{5}$";

	private static Pattern pattern = Pattern.compile(PLATE_NUMBER_FORMAT);

	@Override
	public void initialize(PlateNumberCheck constraintAnnotation) {

	}

	@Override
	public boolean isValid(CharSequence object, ConstraintValidatorContext constraintContext) {
		if (StringUtils.isBlank(object))
			return true;
		
		String input = object.toString().trim().replaceAll(SeaxConstants.HYPHEN, SeaxConstants.EMPTY).toUpperCase();
		boolean valid = false;
		Matcher matcher = pattern.matcher(input);
		if (matcher.matches()) {
			valid = true;
		}

        if(!valid) {
            constraintContext.disableDefaultConstraintViolation();
            constraintContext.buildConstraintViolationWithTemplate(ReturnMsg.PLATE_NUMBER_FORMAT).addConstraintViolation();
        }
        
        return valid;
	}
	
	public static void main(String[] args) {
		String input = "浙A333JX";
//		String input = "WJ0112345";
//		String input = "WJ京12345";
		Matcher matcher = pattern.matcher(input);
		if (matcher.matches()) {
			System.out.println("matched");
		} else {
			System.out.println("failed");
		}
	}

}
